package cn.seaboot.admin.excel.service;

import cn.seaboot.admin.excel.bean.ExcelLog;
import cn.seaboot.admin.excel.bean.ExcelLogItem;
import cn.seaboot.admin.excel.bean.ExcelRow;
import cn.seaboot.admin.excel.bean.ExcelSource;
import cn.seaboot.admin.excel.consts.ExcelStatus;
import cn.seaboot.admin.excel.dao.ExcelLogDao;
import cn.seaboot.admin.excel.dao.ExcelSourceDao;
import cn.seaboot.admin.starter.upload.UploadProperties;
import cn.seaboot.admin.upload.LocalStorage;
import cn.seaboot.admin.upload.OutputInfo;
import cn.seaboot.admin.upload.Uploader;
import cn.seaboot.admin.user.bean.User;
import cn.seaboot.admin.user.context.UserContext;
import cn.seaboot.commons.core.*;
import cn.seaboot.commons.file.FileUtils;
import cn.seaboot.excel.ExcelBook;
import cn.seaboot.excel.call.ExcelCallback;
import cn.seaboot.excel.call.RowReadCallback;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.function.Consumer;

/**
 * Excel管理相关，与业务无关
 * <p>
 * 文件存储，可用于文档管理，业务需求暂无
 *
 * @author Mr.css
 * @version 2019-04-22 15:26:05
 */
@Service
public class ExcelSourceService {
    private final Snowflake snowflake = SnowflakeFactory.createSnowflake();
    private Logger logger = LoggerFactory.getLogger(ExcelSourceService.class);

    private Uploader uploader;

    @Resource
    private UserContext userContext;

    @Resource
    private ExcelSourceDao excelSourceDao;

    @Resource
    private UploadProperties uploadProperties;

    /**
     * 初始化
     *
     * @throws IOException -
     */
    @PostConstruct
    public void init() throws IOException {
        File root = FileUtils.directory(uploadProperties.getExcelPath());
        LocalStorage storage = new LocalStorage(root);
        uploader = new Uploader(storage);
    }

    /**
     * 文件入库，上传后，先保存，再预览，最后生效
     * 此处步骤：文件入库
     *
     * @param file 请求
     * @param type 文件类型-业务类型
     * @return pojo
     * @throws IOException -
     */
    public ExcelSource importExcel(int type, MultipartFile file) throws IOException {
        OutputInfo info = uploader.write(file);

        String filename = file.getOriginalFilename();
        if (CommonUtils.isEmpty(filename)) {
            filename = info.getName();
        }
        filename = StringUtils.truncateHead(filename, 32);

        ExcelSource source = new ExcelSource();
        source.setId(snowflake.nextId());
        source.setUserId(userContext.getUserId());

        source.setExcelStatus(ExcelStatus.UPLOAD);
        source.setExcelType(type);

        source.setExcelType(type);
        source.setExcelName(filename);
        source.setExcelPath(info.getPath());
        excelSourceDao.insert(source);
        return source;
    }

    /**
     * 按ID删除
     *
     * @param id ID
     * @return affected rows
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Long id) throws IOException {
        ExcelSource excel = excelSourceDao.selectById(id);
        Asserts.notNull(excel, "Excel is not found: {}", id);
        int res = excelSourceDao.deleteById(excel.getId(), userContext.getUserId());
        uploader.delete(excel.getExcelPath());
        return res;
    }

    /**
     * 获取输入流
     *
     * @param relativePath 相对路径
     * @return InputStream
     * @throws IOException -
     */
    public InputStream openInputStream(String relativePath) throws IOException {
        return uploader.openInputStream(relativePath);
    }

    /**
     * 获取输入流
     *
     * @param id 文件ID
     * @return InputStream
     * @throws IOException -
     */
    public ExcelSource queryById(Long id) throws IOException {
        return excelSourceDao.selectById(id);
    }

    /**
     * 获取输入流
     *
     * @param id 文件ID
     * @return InputStream
     * @throws IOException -
     */
    public InputStream openInputStreamById(Long id) throws IOException {
        ExcelSource excel = excelSourceDao.selectById(id);
        Asserts.notNull(excel, "Excel is not found: {}", id);
        return uploader.openInputStream(excel.getExcelPath());
    }

    /**
     * 查询列表
     *
     * @return list
     */
    public List<ExcelSource> queryList(String userId) {
        return excelSourceDao.selectList(userId);
    }
}
